<script setup>
import {ref, onMounted} from "vue";
import {deleteArticleById, getAllArticle, getArticleByKeyword} from "@/apis/article";
import {ElMessage, ElMessageBox} from "element-plus";

const articles = ref([])
const keyword = ref('')
const getArticles = async () => {
  await getAllArticle().then(res => {
    articles.value = res.data
    console.log(res)
  })
}
const getArticleByKey = async (keyword) => {
  const res = await getArticleByKeyword(keyword)
  articles.value = res.data
  if (res.code == 200) {
    ElMessage({type: 'success', message: res.message})
  } else if (res.code == 505) {
    ElMessage({type: 'error', message: res.message})
    getArticles()
  } else {
    ElMessage({type: 'error', message: res.message})
    getArticles()
  }
}
const deleteArticle = async (id) => {
  ElMessageBox.confirm(
      '你确定删除该信息吗?',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        await deleteArticleById(id).then(res => {
          console.log(res)
          if (res.code == 200) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            getArticles()
          } else {
            ElMessage({
              type: 'error',
              message: '删除失败',
            })
          }
        })
      }).catch(() => {
    ElMessage({type: 'info', message: '操作取消'})
  })
}
onMounted(() => {
  getArticles()
})

</script>
<template>
  <el-divider/>
  <div class="article">
    <div class="mt-4" style="margin-top: -100px">
      <el-input
          v-model="keyword"
          placeholder="请输入标题"
          class="input-with-select">
        <template #append>
          <el-button @click="getArticleByKey(keyword)">搜索</el-button>
        </template>
      </el-input>
    </div>
    <el-table :data="articles" style="width: 100%;  width:800px;margin: 10px auto;">
      <el-table-column prop="title" label="文章标题" width="180"/>
      <el-table-column prop="createDate" label="创建时间"/>
      <el-table-column label="操作" #default="scope">
        <el-button type="danger" @click="deleteArticle(scope.row.id)">删除</el-button>
      </el-table-column>
    </el-table>
  </div>
</template>
<style scoped>
.article {
  width: 800px;
  margin: 100px auto;
}
</style>